//#include <BleAbsMouse.h>
#define ER "ER\n"
#define OK "OK\n"
#include <BleMouse.h>
//#include <BleKeyboard.h>
BleMouse bleMouse("JuRu ESP32 Mouse", "ESP32 Inc.", 100);
//BleKeyboard bleKeyboard("JuRu ESP32 Keyboard", "ESP32 Inc.", 100);
//BleAbsMouse bleAbsMouse("JuRu ESP32 Mouse", "ESP32 Inc.", 100);
String inputString = ""; 
bool processing = false;

void mouseMove(int x,int y){
  int remainingX = x;
  int remainingY = y;
  while (remainingX != 0 || remainingY != 0) {
    int stepX = constrain(remainingX, -64, 64);
    int stepY = constrain(remainingY, -64, 64);
    bleMouse.move(stepX, stepY, 0);  // 第三个参数是滚轮，可以设为0
    delay(33);
    remainingX -= stepX;
    remainingY -= stepY;
  }
}

void setup() {
  Serial.begin(115200);
  bleMouse.begin();
  //bleMouse.begin();
  //bleKeyboard.begin();
}

void onClick(String command){
  if(!bleMouse.isConnected()) {
    Serial.println(ER);
    return;
  }
  if (!command.startsWith("C:")) {
    Serial.println(ER);
    return;
  }
  processing = true;
  int commaIndex = inputString.indexOf(',');
  if (commaIndex != -1) {
    int x = inputString.substring(2, commaIndex).toInt();
    int y = inputString.substring(commaIndex + 1).toInt();
    mouseMove(-1000,-2000);
    delay(1000);
    mouseMove(x,y); //模拟鼠标左键点击
    delay(300); // 稍作等待
    bleMouse.click(MOUSE_LEFT); //模拟鼠标左键点击
    delay(300);
    Serial.println(OK);
  }else{
    Serial.println(ER);
  }
  processing = false;
}



void loop() {
  // 检查是否有数据从串口发送过来
  if (Serial.available() > 0) {
    // 逐个字符读取串口输入
    char incomingByte = Serial.read();
    // 如果是换行符\n，表示一条完整指令接收完毕
    if (incomingByte == '\n') {
      if(!processing){
        if (inputString.startsWith("C:")) {
          onClick(inputString);
        }else{
          Serial.println(ER);
        }
      }else{
        Serial.println("设备忙");
        Serial.println(ER);
      }
      // 清空接收缓冲区准备接收下一条指令
      inputString = "";
    } else {
      // 将接收到的字符添加到指令字符串中
      inputString += incomingByte;
    }
  }

}
